package com.czl.cloudservice.uploadfile;

import com.czl.cloudservice.utils.UploadFileUtil;
import com.czl.common.redis.RedisUtils;
import com.czl.common.utils.Constant;
import com.czl.common.utils.ResultBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
public class uploadFileController {
    @Value("${path.rooturl}")
    String rootUrl;
    /**
     * 文件上传
     *
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(path = "/fileUpload")
    @ResponseBody
    public ResultBean fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        Map<String, Object> data = new HashMap<String, Object>();
        //这里是拿到文件名
        String fileName = file.getOriginalFilename();
        //这里是拿到文件后缀
        String suffix =fileName.substring(fileName.lastIndexOf("."));
        System.out.println(suffix);
        //获取文件上传路径
        String uploadPath = Constant.FilePath.getUploadPath(suffix);
        if (StringUtils.isNotBlank(uploadPath)){
            //拼接文件配置的上传地址
            String targetDir =Constant.UPLOAD_PATH+uploadPath;
           //  String targetDir ="/Users/haodongjie/IdeaProjects";
            //这里是工具类
            UploadFileUtil.uploadFile(file.getBytes(), targetDir, fileName);
            data.put("fileUrl",rootUrl+ uploadPath + File.separator + fileName);
            data.put("fileType",Constant.FilePath.getUploadIndex(suffix));
            System.out.println(" file ==>" + fileName + "==>upload to " + rootUrl+targetDir + "success");
        }else {
            System.out.println("此文件格式不支持上传！");
            return ResultBean.createResultBean(Constant.StatusCode.ERROR,"此文件格式不支持上传！",data);
        }
        return ResultBean.createResultBean(Constant.StatusCode.OK,data);
    }
}
